import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import useInputFocusContext from '@/context/InputFocusContext';
import { useEffect, useRef, useState } from 'react';

interface Props {
  onCancel(): void;
  onSubmit(title: string): void;
  open: boolean;
  text?: string;
}

export const DialogInput = ({
  open,
  onCancel,
  onSubmit,
  text = 'Ввеидите название подзадачи'
}: Props) => {
  const [value, setValue] = useState('');

  const handleSubmit = () => {
    if (value.length > 0) {
      onSubmit(value);
      setValue('');
    }
  };

  const handleCancel = () => {
    onCancel();
    setValue('');
  };

  const handleKeyEnter = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') handleSubmit();
  }


  const { registerInput } = useInputFocusContext();
  const inputRef = useRef(null);


  useEffect(() => {
    registerInput('NewColumnInBoard', inputRef.current);
  }, [registerInput]);


  return (
    <div onClick={(e) => e.stopPropagation()}>
      <Dialog open={open} onOpenChange={handleCancel}>
        <DialogContent className='sm:max-w-md'>
          <DialogHeader>
            <DialogTitle>{text}</DialogTitle>
          </DialogHeader>
          <div className='flex items-center space-x-2'>
            <Input
              id='subtaskTitle'
              defaultValue={value}
              placeholder='Subtask title'
              onChange={(e) => setValue(e.target.value)}
              onKeyDown={handleKeyEnter}
              // autoComplete='off'
              ref={inputRef}
              name='NewColumnInBoard'
            />
          </div>
          <DialogFooter className='sm:justify-end'>
            <Button type='button' variant='outline' onClick={handleCancel}>
              Отменить
            </Button>
            <Button onClick={handleSubmit}>
              Создать
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};
